package com.ly.imp;

import com.ly.rule.LyResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

/**
 * @author liuyang
 */
public class LyStaticResponse implements LyResponse {

    /**
     * 而这个类主要就是为了实现往通道内里面写数据，所以拿到netty中的通道
     */
    private final HttpRequest request;
    private final ChannelHandlerContext context;

    public LyStaticResponse(HttpRequest request, ChannelHandlerContext ctx) {
        this.request = request;
        this.context = ctx;
    }


    @Override
    public void write(String fileName) throws Exception {

        URI resource = this.getClass().getResource("/" + fileName).toURI();
        File file = new File(resource);
        byte[] b = new byte[(int)file.length()];
        FileInputStream stream = new FileInputStream(file);
        while (true) {
            int read = stream.read(b);
            if (read == -1) {
                break;
            }
            ByteBuf buffer = Unpooled.copiedBuffer(b);
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer
            );
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
            response.headers().set(HttpHeaderNames.ACCEPT_RANGES, "bytes");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
            this.context.writeAndFlush(response);
        }
    }
}
